package com.axzhengxin.platform.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.axzhengxin.platform.business.domain.*;
import com.axzhengxin.platform.business.mapper.*;
import com.axzhengxin.platform.business.service.IBizFlowInfoService;
import com.axzhengxin.platform.homePage.domain.SearchParams;
import com.axzhengxin.platform.homePage.domain.StatisticData;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author ahzj0005
 * @Date 2021/2/22-11:27
 **/
@Slf4j
@Service
public class BizFlowInfoServiceImpl implements IBizFlowInfoService {
    @Autowired
    private BizFlowInfoMapper bizFlowInfoMapper;
    @Autowired
    private BizFlowTaskMapper bizFlowTaskMapper;
    @Autowired
    private BizApplyGuaranteePledgeRelativeMapper pledgeRelativeMapper;
    @Autowired
    private FspCorInfBusinessMapper fspCorInfBusinessMapper;
    @Autowired
    private BizApplyInfoMapper applyInfoMapper;
    @Autowired
    private BizApproveInfoMapper bizApproveInfoMapper;
    @Autowired
    private BizWarrantInfoMapper bizWarrantInfoMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserMapper userMapper;

    @Value("${systemConfig.ahjr_service_url:#{null}}")
    private String ahjr_service_url;

    /**
     * 抵押创建
     */
    private String pledgeCreate = "PLEDGE_CREATE";
    /**
     * 抵押解除
     */
    private String pledgeDisable = "PLEDGE_DISABLE";
    /**
     * 授信
     */
    private String approve = "APPROVE";
    /**
     * 申请
     */
    private String apply = "APPLY";
    /**
     * 放款
     */
    private String loan = "LOAN";
    /**
     * 担保
     */
    private String guarantee = "GUARANTEE";

    @Override
    public int distributeApply(String userId, String reqId, String flowUid) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long currentUserId = user.getUserId();
        //更新路程INFO
        SysUser mysqlUser = userMapper.selectUserById(Long.valueOf(userId));
        Long deptId = user.getDeptId();
        Long mysqlDeptId = mysqlUser.getDeptId();
        String currentDeptId = null;
        if (!deptId.equals(mysqlDeptId)) {
            currentDeptId = String.valueOf(mysqlDeptId);
        }
        updateFlowInfoBizTypeAndStatus(1010, "APPLY", flowUid, userId, currentDeptId);

        //新增流程节点
        BizFlowTask bizFlowTask = new BizFlowTask();
        bizFlowTask.setCreateTime(new Date());
        bizFlowTask.setCreateBy(user.getUserId().toString());
        bizFlowTask.setNextUserId(userId);
        //将流程起始修改指定下一UserId,修改上一节点最终流程节点标志为0

        bizFlowTaskMapper.updateByFlowUid(userId, flowUid);
        //延续插入新的流程节点
        bizFlowTask.setFlowUid(flowUid);
        bizFlowTask.setUserId(String.valueOf(currentUserId));
        bizFlowTask.setBizType("APPLY");
        bizFlowTask.setStatus(1010);
        int i = bizFlowTaskMapper.insertBizFlowTask(bizFlowTask);
        return i;
    }

    @Override
    public Record getRecordList(String reqId, String flowUid) {
        String deptId = bizFlowInfoMapper.selectDeptIdByFlowUid(flowUid);
        List<BizFlowInfoVo> recordList = bizFlowInfoMapper.getRecordList(reqId, deptId);
        List<BizFlowInfoVo> records = new ArrayList<>();
        records.add(recordList.get(0));
        for (int i = 1; i < recordList.size(); i++) {
            Integer status = recordList.get(i).getStatus();
            if (status == 2000 || status == 3000) {
                records.add(recordList.get(i));
            }
        }
        int j = 4 - records.size();
        Record record = new Record();
        record.setSize(records.size());
        for (int i = 0; i < j; i++) {
            BizFlowInfoVo bizFlowInfoVo = new BizFlowInfoVo();
            records.add(bizFlowInfoVo);
        }
        record.setBizFlowInfoVoList(records);
        return record;
    }


    /**
     * 审核
     * 1.新增Task节点
     * 2.更新上一Task的lastFlag和nextUserId
     * 3.若果是APPLY流程通过  新增授信内容
     *
     * @param bizFlowTaskParams
     */
    @Override
    @Transactional
    public AjaxResult auditing(BizFlowTask bizFlowTaskParams) {
        Integer status = bizFlowTaskParams.getStatus();
        //获取处理人信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String currentUserId = String.valueOf(user.getUserId());
        String currentDeptId = String.valueOf(user.getDeptId());
        String financeId = String.valueOf(user.getDept().getFinanceId());
        BizFlowTask bizFlowTask = bizFlowTaskMapper.getBizFlowTaskByFlowUid(bizFlowTaskParams.getFlowUid());
        BizApplyInfo bizApplyInfo = applyInfoMapper.selectBizApplyInfoById(bizFlowTask.getBizId());
        String bizType = bizFlowTask.getBizType();
        String flowUid = bizFlowTask.getFlowUid();
        bizFlowTask.setUserId(currentUserId);
        bizFlowTask.setCreateBy(currentUserId);
        bizFlowTask.setCreateTime(new Date());
        bizFlowTask.setStatus(bizFlowTaskParams.getStatus());

        String isUrgentLoan = "0";
        if (apply.equals(bizType)) {
            System.out.println("====================开始传递审核结果===================");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("reqNo", bizApplyInfo.getReqId());
            String flag = "1";
            if (status == 3000) {
                flag = "2";
            }
            if (apply.equals(bizType)) {
                jsonObject.put("flag", flag);
                //是否首贷！！！
                jsonObject.put("isFirstLoan", "0");
                //0-非应急贷款,1-应急贷款
                jsonObject.put("isLoan", isUrgentLoan);
                JSONObject audit = ahjrService(jsonObject, "audit");
                Integer code = (Integer) audit.get("code");
                if (200 != code) {
                    System.out.println("*************中小微平台数据更新失败*************");
                    System.out.println(audit.get("msg"));
                    System.out.println("*************中小微平台数据更新失败************");
                    return AjaxResult.error("中小微平台数据更新失败:" + audit.get("msg"));
                }
            }
        }
        if (approve.equals(bizType) && status == 2000) {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("reqNo", bizApplyInfo.getReqId());
            jsonObject1.put("flag", "1");
            String loanType = "3";
            String bizId = bizFlowTaskParams.getBizId();
            BizApplyInfo bizApplyInfo1 = new BizApplyInfo();
            bizApplyInfo1.setReqId(bizId);
            List<BizApproveInfo> bizApproveInfoList = bizApproveInfoMapper.selectBizApproveInfoByReqId(bizApplyInfo1);
            BizApproveInfo info = bizApproveInfoList.get(0);
            String creditAmount = info.getApproveAmount().toPlainString();
            if (null != creditAmount && !"".equals(creditAmount)) {
                BigDecimal bigDecimal = new BigDecimal(creditAmount);
                bigDecimal = bigDecimal.multiply(new BigDecimal(10000));
                creditAmount = bigDecimal.toPlainString();
            }
            jsonObject1.put("contractNo", info.getApproveContractNo());
            jsonObject1.put("guaranteeType", loanType);
            jsonObject1.put("guaranteeRatio", "0");
            //warn.getDelay()  放款利率
            jsonObject1.put("delay", "0");
            //授信金额
            jsonObject1.put("amt", creditAmount);
            jsonObject1.put("operationTime", new Date());
            //是否首贷
            jsonObject1.put("isFirstLoan", "0");
            //授信起始
            jsonObject1.put("startDate", info.getApproveStart());
            //授信结束
            jsonObject1.put("endDate", info.getApproveEnd());
            //0-非应急贷款,1-应急贷款
            jsonObject1.put("isLoan", isUrgentLoan);
            System.out.println("=====================开始调用授信接口======================");
            JSONObject credit = ahjrService(jsonObject1, "credit");
            Integer code = (Integer) credit.get("code");
            if (200 != code) {
                System.out.println("*************中小微平台数据更新失败*************");
                System.out.println(credit.get("msg"));
                System.out.println("*************中小微平台数据更新失败************");
                return AjaxResult.error("中小微平台数据更新失败:" + credit.get("msg"));
            }
        }
        updateFlowInfoBizTypeAndStatus(status, bizType, flowUid, currentUserId, null);
        bizFlowTaskMapper.updateByFlowUid(currentUserId, flowUid);
        bizFlowTaskMapper.insertBizFlowTask(bizFlowTask);
        int code = 2000;
        if (status == code) {
            if (apply.equals(bizType) || approve.equals(bizType)) {
                //新增流程INFO，指向下一环节流程
                BizFlowInfo bizFlowInfo = new BizFlowInfo();
                bizFlowInfo.setBizId(bizFlowTask.getBizId());
                bizFlowInfo.setCurrentNodeDeptId(currentDeptId);
                bizFlowInfo.setCurrentNodeUserId(currentUserId);
                bizFlowInfo.setStatus(1010);
                if (apply.equals(bizType)) {
                    bizFlowInfo.setBizType(approve);
                } else if (approve.equals(bizType)) {
                    bizFlowInfo.setBizType(loan);
                }
                bizFlowInfo.setCreateBy(currentUserId);
                bizFlowInfo.setFinanceId(financeId);
                bizFlowInfoMapper.insertBizFlowInfo(bizFlowInfo);
                bizFlowTask.setFlowUid(bizFlowInfo.getFlowUid());
                bizFlowTask.setStatus(1010);
                if (apply.equals(bizType)) {
                    bizFlowTask.setBizType(approve);
                } else if (approve.equals(bizType)) {
                    bizFlowTask.setBizType(loan);
                }
                bizFlowTaskMapper.updateByFlowUid(currentUserId, flowUid);
                bizFlowTaskMapper.insertBizFlowTask(bizFlowTask);

            }
            if (guarantee.equals(bizType)) {
                //担保审核通过时，修改实际担保金额、担保期限、担保利率
                BizWarrantInfo bizWarrantInfo = new BizWarrantInfo();
                String warrantId = bizFlowTaskParams.getWarrantId();
                BigDecimal guaranteeAmount = bizFlowTaskParams.getGuaranteeAmount();
                bizWarrantInfo.setWarrantId(warrantId);
                BizWarrantInfo search = bizWarrantInfoMapper.selectBizWarrantInfoById(warrantId);
                BigDecimal approveAmount = search.getApproveAmount();
                int i = approveAmount.compareTo(guaranteeAmount);
                if (i < 0) {
                    return AjaxResult.error("担保金额设置过大,最高设置" + approveAmount.setScale(2, RoundingMode.HALF_UP) + "万元!");
                }
                bizWarrantInfo.setGuaranteeAmount(guaranteeAmount);
                bizWarrantInfo.setGuaranteeTime(bizFlowTaskParams.getGuaranteeTime());
                bizWarrantInfo.setGuaranteeRadio(bizFlowTaskParams.getGuaranteeRadio());
                bizWarrantInfo.setGuaranteeNo(bizFlowTaskParams.getGuaranteeNo());
                bizWarrantInfoMapper.updateBizWarrantInfo(bizWarrantInfo);
            }
        }
        return AjaxResult.success("操作成功");
    }


    @Override
    public void backApply(String flowUid) {
        //获取处理人信息
        BizFlowTask task = bizFlowTaskMapper.getBizFlowTaskByFlowUid(flowUid);
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //新增流程节点具体
        String nextUserId = task.getNextUserId();
        String currentUserId = task.getUserId();
        SysUser nextUser = userMapper.selectUserById(Long.valueOf(nextUserId));
        SysUser currentUser = userMapper.selectUserById(Long.valueOf(currentUserId));
        String deptId = null;
        if (!nextUser.getDeptId().equals(currentUser.getDeptId())) {
            deptId = String.valueOf(currentUser.getDeptId());
        }
        updateFlowInfoBizTypeAndStatus(10, "APPLY", flowUid, currentUserId, deptId);
        bizFlowTaskMapper.updateByFlowUid(nextUserId, flowUid);
        BizFlowTask bizFlowTask = new BizFlowTask();
        bizFlowTask.setUserId(currentUserId);
        bizFlowTask.setCreateBy(String.valueOf(userId));
        bizFlowTask.setRemark("退回");
        bizFlowTask.setFlowUid(flowUid);
        bizFlowTask.setBizType("APPLY");
        bizFlowTask.setStatus(10);
        bizFlowTaskMapper.insertBizFlowTask(bizFlowTask);
    }

    /**
     * 待审核订单可以收回或退回  收回操作
     *
     * @param flowUid 流程id
     */
    @Override
    public void getBackApply(String flowUid) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        BizFlowTask task = bizFlowTaskMapper.getBizFlowTaskByFlowUid(flowUid);
        String dealUserId = task.getUserId();
        String nextUserId = task.getNextUserId();
        Integer status = task.getStatus();


        updateFlowInfoBizTypeAndStatus(10, "APPLY", flowUid, dealUserId, String.valueOf(user.getDeptId()));
        bizFlowTaskMapper.updateByFlowUid(nextUserId, flowUid);
        BizFlowTask bizFlowTask = new BizFlowTask();
        bizFlowTask.setFlowUid(flowUid);
        bizFlowTask.setUserId(dealUserId);
        bizFlowTask.setRemark("收回");
        bizFlowTask.setBizType("APPLY");
        bizFlowTask.setStatus(10);
        int j = bizFlowTaskMapper.insertBizFlowTask(bizFlowTask);
    }

    @Override
    public List<BizApplyGuaranteePledgeRelative> getGuaranteeList(String reqId) {
        BizApplyGuaranteePledgeRelative relative = new BizApplyGuaranteePledgeRelative();
        relative.setApplyId(reqId);
        return pledgeRelativeMapper.selectBizApplyGuaranteePledgeRelativeList(relative);
    }

    @Override
    public FspCorInfBusiness getCustomerDetail(String customerId) {
        return fspCorInfBusinessMapper.selectFspCorInfById(customerId);
    }

    @Override
    @DataScope(deptAlias = "sd", userAlias = "uu")
    public int getTaskAgentCount(SearchParams searchParams) {
        return bizFlowInfoMapper.getTaskAgentCount(searchParams);
    }

    @Override
    public List<StatisticData> getAuditingStatistic() {
        return bizFlowInfoMapper.getAuditingStatistic();
    }

    public String format(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    public void updateFlowInfoBizTypeAndStatus(Integer status, String bizType, String flowUid, String userId, String currentDeptId) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("bizType", bizType);
        map.put("flowUid", flowUid);
        map.put("userId", userId);
        map.put("currentDeptId", currentDeptId);
        bizFlowInfoMapper.updateFlowInfoBizTypeAndStatus(map);
    }


    /**
     * 验证验证码
     *
     * @param phone     手机号
     * @param phoneCode 验证码
     * @return
     */
    public boolean checkPhoneCode(String phone, String phoneCode, String key) {
        String redisCode = redisCache.getCacheObject(phone + key);
        return phoneCode.equals(redisCode);
    }


    public JSONObject ahjrService(JSONObject jsonObject, String serviceid) {
        System.out.println("===============开始执行与中小微平台交互接口: [" + serviceid + "]  =======================");
        Long userId = null;
        SysUser user = null;
        try {
            userId = SecurityUtils.getLoginUser().getUser().getUserId();
        } catch (Exception e) {

        }

        if (null != userId) {
            user = userMapper.selectUserById(userId);
        }
        String url = ahjr_service_url + serviceid;

        jsonObject.put("financeId", null == userId ? "000000" : user.getDept().getFinanceId());
        jsonObject.put("channel", "zxfwzx");
        jsonObject.put("contractNo", "1");
        jsonObject.put("loanContractNo", "1");
        System.out.println("==============交互请求报文=============");
        System.out.println(jsonObject.toJSONString());

        String resultStr = "";
        try {
            String jsonString = JSONObject.toJSONString(jsonObject);
            resultStr = HttpUtils.sendPost(url, jsonString, "application/json");
            System.out.println("==============交互响应报文=============");
            System.out.println(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (resultStr != null) {
            JSONObject object = JSONObject.parseObject(resultStr);
            return object;
        }
        return null;
    }
}
